<template>
    <div>

        <!-- 查询条件 -->
        <el-card>
            <el-button type="default" size="default" v-for="item in buttonList" :key="item.PId"
                @click="dynamicFunction(item.PId)">{{
                item.PName
            }}</el-button>
            <el-form :model="condition" label-width="100px" :inline="true" size="normal" style="float:right">
                <!-- 按钮权限 -->
                <el-form-item>
                    <el-input class="el-icon-search" placeholder="请输入角色名称" v-model="condition.roleName"
                        @change="handleCurrentChange(1)"></el-input>
                </el-form-item>
            </el-form>

            <!-- 弹出层 -->
            <el-dialog v-model="roleAddDialog" title="角色添加" width="600">
                <span>
                    <el-form :model="roleForm" label-width="100px" :inline="false" size="normal">
                        <el-form-item label="角色名称">
                            <el-input v-model="roleForm.RoleName"></el-input>
                        </el-form-item>
                        <el-form-item label="角色权限">
                            <!-- 权限树 -->
                            <el-tree style="max-width: 600px" :data="permissionTree.values" show-checkbox node-key="PId"
                                ref="treeRef" :props="defaultProps" />

                        </el-form-item>
                    </el-form>

                </span>
                <span slot="footer">
                    <el-button @click="roleAddDialog = false">取消</el-button>
                    <el-button type="primary" @click="roleAdd">确认</el-button>
                </span>
            </el-dialog>


        </el-card>
        <!-- 列表显示 -->
        <!-- {{ multipleSelection }} -->
        <el-card>
            <el-table :data="roleList" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center">
                </el-table-column>
                <!-- <el-table-column prop="RoleId" label="角色Id" align="center">
                </el-table-column> -->
                <el-table-column prop="RoleName" label="角色" align="center">
                </el-table-column>
                <el-table-column prop="CreateTime" label="创建时间" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template v-slot="scope">

                        <el-link @click="getRolePermission(scope.row.RoleId)">修改权限</el-link>
                        <!-- 反填权限树 -->
                        <el-dialog v-model="rolePermissionDialog" title="修改角色权限" width="600">
                            <!-- 权限树 -->
                            <el-tree style="max-width: 700px" :data="permissionTree.values" show-checkbox node-key="PId"
                                ref="treeRef2" :props="defaultProps" :check-strictly="true" />
                            <span slot="footer">
                                <el-button @click="rolePermissionDialog = false">取消</el-button>
                                <el-button type="primary" @click="updRolePermissions()">
                                    确认 </el-button>
                            </span>
                        </el-dialog>
                    </template>
                </el-table-column>
            </el-table>

        </el-card>
        <el-card>
            <!-- 分页 -->
            <table style="margin: 5px auto;">
                <tbody>
                    <tr>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="total, slot,sizes" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <span class="el-pagination__total is-first">&nbsp;共计{{ pager.pageCount }}页,当前{{
                pager.pageIndex
            }}/{{ pager.pageCount }}页</span>
                            </el-pagination>
                        </td>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="slot, prev, pager" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <button @click="handleCurrentChange(1)" :disabled="pager.pageIndex == 1"
                                    class="btn-prev">首页</button>
                            </el-pagination></td>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="slot, next, jumper" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <button @click="handleCurrentChange(pager.pageCount)"
                                    :disabled="pager.pageIndex == pager.pageCount" class="next-prev">尾页</button>
                            </el-pagination></td>
                    </tr>
                </tbody>
            </table>
        </el-card>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { onMounted } from 'vue'


import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
//import { ElTree } from 'element-plus'
import { ElMessageBox } from 'element-plus'
//import { DefineComponent } from 'vue';
import { loginStore } from "@/stores/login"

import axios from 'axios';
import { baseURL_dev } from '@/config/baseURL'

const baseURL = baseURL_dev
axios.defaults.baseURL = baseURL;

const Route = useRoute()
const store = loginStore();

const roleList = ref([])
const condition = reactive({
    roleName: ''
})
const buttonList = ref([])
const pager = reactive({
    pageIndex: 1,
    pageSize: 10,
    pageCount: 0,
    totalCount: 0,
})
//角色弹出层变量
const roleAddDialog = ref(false)

function getRoleList() {
    axios.get("Role/PageQuery", {
        params: {
            roleName: condition.roleName,
            pageIndex: pager.pageIndex,
            pageSize: pager.pageSize
        }
    }).then(res => {
        roleList.value = res.data.Data
        pager.pageCount = res.data.PageCount
        pager.totalCount = res.data.TotalCount
    })
}
function handleSizeChange(size) {
    pager.pageSize = size;
    getRoleList();
}
function handleCurrentChange(index) {
    pager.pageIndex = index;
    getRoleList();
}
//根据路径获取按钮权限
function getButtonPermissionsByPath() {
    let empId = '';
    if (store.getUserInfo().IsTenant) {
        empId = store.getUserInfo().TenantId + 'admin'
    }
    else {
        empId = store.getUserInfo().UId
    }
    axios.get("Permission/GetButtonPermissionsByPath", {
        params: {
            empId: empId,
            path: Route.fullPath
        }
    }).then(res => {
        buttonList.value = res.data.Data;
    })
}

//动态方法
function dynamicFunction(pid) {
    if (pid == "M3002001") {
        roleAddDialog.value = true;
    }
    if (pid == "M3002002") {
        //批量删除
        batchDel();

    }
}
const roleForm = reactive({
    RoleId: 0,
    RoleName: "",
    //"createTime": "",
    PIds: []
})
interface ListMenu {
    PId: number,
    PName: string,
    ParentId: string,
    Path: string,
    Icon: string,
    Children: ListMenu[]
}
const permissionTree = reactive<ListMenu[]>([])
const defaultProps = {
    children: 'Children',
    label: 'PName',
    id: "PId"
}
//获取权限树
function getPermissionTree() {
    axios.get("Permission/GetAllMenus").then(res => {
        permissionTree.values = res.data.Data;
        //console.log(permissionTree)
    })
}
const treeRef = ref<InstanceType<typeof ElTree>>()

//角色添加
function roleAdd() {
    roleForm.PIds = treeRef.value!.getCheckedKeys();
    console.log(roleForm)
    axios.post("Role/RoleAdd", roleForm).then(res => {
        if (res.data.Code == 200) {
            ElMessage.success("添加成功");
            //清空已选择
            treeRef.value!.setCheckedKeys([], false);
            handleCurrentChange(1)
            //关闭弹出层
            roleAddDialog.value = false;
        }
        else {
            ElMessage.error(res.data.Msg);
        }
    })
}
const multipleSelection = ref([])
//批量删除
function batchDel() {
    if (multipleSelection.value.length == 0) {
        ElMessage.error("至少选中一项");
        return;
    }
    ElMessageBox.confirm("确定要删除吗？", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "danger",
    }).then(() => {
        axios.post("Role/BatchDelRoles", multipleSelection.value
        ).then(res => {
            if (res.data.Code == 200) {
                ElMessage.success("删除成功");
                handleCurrentChange(1)
            }
            else {
                ElMessage.error(res.data.Msg);
            }
        })
    }).catch(() => { })
    //确定
    //console.log(multipleSelection.value)
}

function handleSelectionChange(val: any) {
    multipleSelection.value = val;
}
//修改权限
const rolePermissionDialog = ref(false)
//const rolePermissionList = ref([])
const treeRef2 = ref<InstanceType<typeof ElTree>>()
const roleId = ref(0)
//获取角色权限
function getRolePermission(roleid: number) {
    rolePermissionDialog.value = true;
    //获取反填树
    axios.get("Permission/GetPermissionsByRoleId?roleId=" + roleid).then(res => {
        //rolePermissionList.value = res.data.Data;
        //获取pid[]
        roleId.value = roleid;
        //console.log(res.data.Data)
        let pidArray = res.data.Data.map(item => item.PId);
        //设置已选
        treeRef2.value!.setCheckedKeys(pidArray, true);
        //treeRef2.value!.setChecked(pidArray, true, true);
    })
}

//修改角色权限
function updRolePermissions() {
    let pids = treeRef2.value!.getCheckedKeys().join(",");

    let halfPids = treeRef2.value!.getHalfCheckedKeys().join(",");
    pids = pids + ',' + halfPids;
    console.log(pids)
    axios.post(`Permission/UpdRolePermissions?roleId=${roleId.value}&pIds=${pids}`).then(res => {
        if (res.data.Code == 200) {
            ElMessage.success("修改成功");
            //刷新页面按钮
            getButtonPermissionsByPath();
            rolePermissionDialog.value = false;
        }
        else {
            ElMessage.error(res.data.Msg);
        }
    })
}

onMounted(() => {
    getRoleList()
    getPermissionTree()
    getButtonPermissionsByPath()

})
</script>
<style scoped>
.el-card {
    margin-bottom: 20px;
}
</style>